package queue

import "fmt"

type CircularQueue struct {
	q        []interface{}
	capacity int
	head     int
	tail     int
}

// 数组环形队列

func NewCircularQueue(n int) *CircularQueue {
	if n == 0 {
		return nil
	}
	return &CircularQueue{
		make([]interface{}, n),
		n,
		0,
		0,
	}
}

func (that *CircularQueue) IsEmpty() bool {
	if that.head == that.tail {
		return true
	}
	return false
}

func (that *CircularQueue) IsFull() bool {
	if that.head == (that.tail+1)%that.capacity {
		return true
	}
	return false
}

func (that *CircularQueue) EnQueue(v interface{}) bool {
	if that.IsFull() {
		return false
	}
	that.q[that.tail] = v
	that.tail = (that.tail + 1) % that.capacity
	return true
}

func (that *CircularQueue) DeQueue() interface{} {
	if that.IsEmpty() {
		return nil
	}
	v := that.q[that.head]
	that.head = (that.head + 1) % that.capacity
	return v
}

func (that *CircularQueue) Print() string {
	if that.IsEmpty() {
		return ""
	}
	result := "head"
	var i = that.head
	for {
		result += fmt.Sprintf("<-%+v", that.q[i])
		i = (i + 1) % that.capacity
		if i == that.tail {
			break
		}
	}
	result += "<-tail"
	return result
}
